package edu.msu.project3.geodraw;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

public class MainActivity extends Activity {
	
	private LocationManager locationManager = null;
    
    /**
     * Request code when selecting a picture
     */
    private static final int PICK_COLOR = 2;

    /*
	 * Current positions values
	 */
    private double latitude = 0.0;
    private double longitude = 0.0;
    
    
    private int maxLineWidth=30;
    
    /*
     * Initial position
     */
    private double startLat = 0;
    private double startLong = 0;
    private boolean coordInit = true;
    
    /*
     * Drawing bounds in pixels
     */
    private int canvasWidth = 0;
    private int canvasHeight = 0;
    

    
    private ActiveListener activeListener = new ActiveListener();
    
    private DrawingView drawingView;
    
    private static final int MAXLATRANGE = 50; // meters (~ 40ft)
    private float maxLongRange = 0.0f;
    
    float[] results = new float[1];
    //is the draw button pressed
    private boolean isDrawing=false;
    //is the accelorometer good to go with the range
    
    private Sensor accelSensor = null;
    private AccelListener accelListener = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		drawingView = (DrawingView)findViewById(R.id.drawingView);
		
//		viewLatitude = (TextView)findViewById(R.id.textLatitude);
//		viewLongitude = (TextView)findViewById(R.id.textLongitude);
		
		// Force the screen to say on and bright
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		
		// Get the location manager
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		setUI();  
	}

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}
	
	public void onDraw(View view) {
		
		isDrawing=true;
		drawingView.clearCoordinates();
		
		canvasWidth = drawingView.getWidth();
		canvasHeight = drawingView.getHeight();
		
		maxLongRange = ((float)canvasWidth/(float)canvasHeight) * MAXLATRANGE;
		
		startLat = latitude;
    	startLong = longitude;
		
		updateView();
	}
	
	 private void setUI() {
//		 if(!valid) {
//				viewLatitude.setText("");
//				viewLongitude.setText("");
//			}
//			else {
//				viewLatitude.setText(String.valueOf(latitude));
//				viewLongitude.setText(String.valueOf(longitude));
				
//				float [] results = new float[1];
//				Location.distanceBetween(latitude, longitude, toLatitude, toLongitude, results);
			//}
	 }
	 
	 private class ActiveListener implements LocationListener {

	        @Override
	        public void onLocationChanged(Location location) {
	            onLocation(location);
	        }

	        @Override
	        public void onProviderDisabled(String provider) {
	            registerListeners();
	        }

	        @Override
	        public void onProviderEnabled(String provider) {
	            // TODO Auto-generated method stub
	            
	        }

	        @Override
	        public void onStatusChanged(String provider, int status, Bundle extras) {
	            // TODO Auto-generated method stub
	            
	        }

	        
	    };
	    
   
	    private class AccelListener implements SensorEventListener {
	    	private float y = 0;
	    	private float a = 0.95f;
	    	
	    	@Override
	    	public void onAccuracyChanged(Sensor sensor, int accuracy){
	    		
	    	}
	    	@Override
	    	public void onSensorChanged(SensorEvent event) {
	    		y= (1.0f -a )* event.values[1] + a*y;

	    		
	    		if(y<0.0f){
	    			y=0.0f;
	    		}

	    		float drawLaw= (1.0f-y/10.0f)*maxLineWidth;
	    		drawingView.SetAllowDraw(y<8.0f);
	    		drawingView.SetLineWidth(drawLaw);
	    	}
    	};
	    
	    private void registerListeners() {
	    	unregisterListeners();
	    	
	    	// Create a Criteria object
	        Criteria criteria = new Criteria();
	        criteria.setAccuracy(Criteria.ACCURACY_FINE);
	        criteria.setPowerRequirement(Criteria.POWER_HIGH);
	        criteria.setAltitudeRequired(true);
	        criteria.setBearingRequired(false);
	        criteria.setSpeedRequired(false);
	        criteria.setCostAllowed(false);
	        
	        String bestAvailable = locationManager.getBestProvider(criteria, true);

	        if(bestAvailable != null) {
	            locationManager.requestLocationUpdates(bestAvailable, 500, 1, activeListener);
//	            TextView viewProvider = (TextView)findViewById(R.id.textProvider);
//	            viewProvider.setText(bestAvailable);
	            Location location = locationManager.getLastKnownLocation(bestAvailable);
	            onLocation(location);
	        }
	        
	        
	        SensorManager sensorManager =
	        		(SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
    		accelSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    		if(accelSensor != null) {
        		accelListener = new AccelListener();
        		sensorManager.registerListener(accelListener, accelSensor,SensorManager.SENSOR_DELAY_GAME);
        	}
	    }
	    
	    private void unregisterListeners() {
	    	locationManager.removeUpdates(activeListener);
	    	
	    	if(accelSensor != null) {
		        SensorManager sensorManager =
		        		(SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
	    		sensorManager.unregisterListener(accelListener);
	    		accelListener = null;
	    		accelSensor = null;
    		}
	    }
	    
	    private void onLocation(Location location) {
	        if(location == null) {
	            return;
	        }
	        
	        latitude = location.getLatitude();
	        longitude = location.getLongitude();
	        
	        if(coordInit) {
	        	startLat = latitude;
	        	startLong = longitude;
	        	
	        	coordInit = false;
	        }
	        if (latitude != 0 && longitude !=0 && isDrawing){
	        	updateView();	
	        }
	        

	        setUI();
	    } 
	    private void updateView() {
	    	// Get the longitude (x) distance
	    	Location.distanceBetween(startLat, startLong, startLat, longitude, results);
	    	float longDist = results[0];
	    	
	    	// Get the latitude (y) distance
	    	Location.distanceBetween(startLat, startLong, latitude, startLong, results);
	    	float latDist = results[0];
	    	
	    	// Keep our signs right for our screen
	    	if(longitude < startLong)
	    		longDist = -longDist;
	    	// For y a negative value indicates a point above the starting point, positive is below
	    	if(latitude > startLat)
	    		latDist = -latDist;
	    	/*
	    	if (longDist == 0){
	    		longDist = 1;
	    	}
	    	if (latDist == 0){
	    		latDist = 1;
	    	}
	    	*/
	    	
	    	// Convert to relative location and send off to the view
	    	drawingView.updatePosition(longDist/(maxLongRange/2), latDist/(MAXLATRANGE/2));
	    }
	    
	    /**
	     * The activity is being paused
	     */
	    @Override
	    protected void onPause() {
	        unregisterListeners();
	        super.onPause();
	    }

	    /**
	     * The activity is being resumed
	     */
	    @Override
	    protected void onResume() {
	        super.onResume();
	        registerListeners();
	    }

		public int getCanvasWidth() {
			return canvasWidth;
		}

		public void setCanvasWidth(int canvasWidth) {
			this.canvasWidth = canvasWidth;
		}

		public int getCanvasHeight() {
			return canvasHeight;
		}

		public void setCanvasHeight(int canvasHeight) {
			this.canvasHeight = canvasHeight;
		}
		
		public void onSubmit(View view) {
			ViewSender sender = new ViewSender();
			sender.sendView(this, drawingView, "Monopoly");
		}

	    /**
	     * Handle a Color button press
	     * @param view
	     */
	    public void onColor(View view) {
	    	onPause();
	        // Get a color from color select activity
	        Intent intent = new Intent(this, ColorSelectActivity.class);

	        startActivityForResult(intent, PICK_COLOR);
	    }

		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);

	        if(requestCode == PICK_COLOR && resultCode == Activity.RESULT_OK) {
	            int result=data.getIntExtra("color", 0);
	            // TODO: set pen color
	            drawingView.setLinePaintColor(result);

	            Log.i("result", Integer.toString(result));
	        }
		}
}
